package yxy.game.pm2.command.union.leader;

import yxy.cherry.data.string.GameString;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.module.RedisLock;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.UnionLeaderMessage;
import yxy.game.pm2.module.union.UnionBean;
import yxy.game.pm2.module.union.UnionHandle;
import yxy.game.pm2.module.union.UnionHandle.UnionPlayerEntry;
import yxy.game.pm2.module.union.UnionLog;

/** 联盟盟主 联盟任免副盟主 */
@MessageType(proto = Command.UnionVice, classtype = UnionLeaderMessage.UnionViceRequest.class)
public class CMD_UnionVice extends Command<UnionLeaderMessage.UnionViceRequest> {

	@Override
	public void execute(MessageSource messageSource, UnionLeaderMessage.UnionViceRequest request) {
		String playerCode = messageSource.getTag();
		String code = request.getCode();

		UnionLeaderMessage.UnionViceResponse.Builder response = UnionLeaderMessage.UnionViceResponse.newBuilder();

		// 盟主权限
		UnionPlayerEntry entry = new UnionPlayerEntry(playerCode);
		Result result = new UnionHandle().checkPlayerUnionLeader(entry);
		if (!result.equals(Result.UnionLeader)) {
			send(messageSource, response, result);
			return;
		}
		RedisLock uLock = UnionBean.lock(entry.getUnionBean().getCode());
		try {
			if (uLock.tryLock()) {
				UnionBean union = entry.reloadUnionBean();
				if (union.getViceList().contains(code)) {
					// 罢免
					union.getViceList().remove(code);
					union.getMemberList().add(code);

					// 联盟日志
					PlayerBean player = PlayerBean.get(entry.getPlayerCode());
					PlayerBean vice = PlayerBean.get(code);
					UnionLog.add(union.getCode(), GameString.联盟日志副盟主免职(player.getName(), vice.getName()).getText());
				} else if (union.getMemberList().contains(code)) {
					if (union.getViceList().size() >= 3) {
						send(messageSource, response, Result.UnionViceUpper);// 副会长满了
						return;
					}
					// 任职
					union.getMemberList().remove(code);
					union.getViceList().add(code);

					// 联盟日志
					PlayerBean player = PlayerBean.get(entry.getPlayerCode());
					PlayerBean vice = PlayerBean.get(code);
					UnionLog.add(union.getCode(), GameString.联盟日志职位变更(player.getName(), vice.getName()).getText());
				} else {
					send(messageSource, response, Result.UnionTargetNotMember);// 这个人不是联盟成员
					return;
				}

				union.set();
				union.active();

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			uLock.unlock();
		}
	}

	private void send(MessageSource messageSource, UnionLeaderMessage.UnionViceResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}